<?php
// ********************************************
// 
// Фотографии.
//
// ********************************************
require_once('tools.class.php');
require_once('upload.class.php');

class CarImages 
{
    protected $db;
    private static $error = '<b>Извините. </b>На сайте возникли трудности технического характера.<br>Обратитесь за помощью к администратору сайта.';

    public function __construct( $database_handler) {
        $this->db = $database_handler;
    }
    
	private static function headers_echo() {
		header('Pragma: no-cache');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Content-Disposition: inline; filename="files.json"');
		header('X-Content-Type-Options: nosniff');
		header('Access-Control-Allow-Origin: *');
		header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
		header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');
	}
	
	private static function FullUrl() {
	return
		(isset($_SERVER['HTTPS']) ? 'https://' : 'http://').
		(isset($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
		(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
		(isset($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT'] === 443 ||
		$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
		substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
	}
    
	public function Update()
    {

        $car_id   = isset($_REQUEST["car_id"]) ? strip_tags($_REQUEST["car_id"]) : '';
        $errmess = "";
		$errcode = 0;
        $data = array();
        
		self::headers_echo();
		if( $_SERVER['REQUEST_METHOD'] != 'POST' ) {
			header('HTTP/1.1 405 Method Not Allowed');
			return;
		}
		
        while (true)
        {
			if( !isset( $_SESSION['cust_id'] ) || !$_SESSION['cust_id'] ) {
				$errmess = "Вы не выполнили вход в систему<br>или Ваша сессия закончилась по таймауту."; 
				$errcode = 999; break;
			}
			$cust_id =  $_SESSION['cust_id'];

			if ( !is_numeric($car_id) ) {
                $errmess = "Нарушение формата данных.";
				$errcode = 2; break;
            }
            if( $this->db == NULL ) {
                $errmess = self::$error;
				$errcode = 1; break;
            }
            $db = $this->db;
                        
// Проверяем существование
            $sqlreq = "SELECT COUNT(*) AS count FROM cars WHERE owner_id=" . $cust_id . " AND car_id=" . $car_id;
            $recset = $db->query( $sqlreq );
            $row = $recset->fetch(PDO::FETCH_ASSOC);
            $count = $row['count'];
            $recset->closeCursor();
            if ($count != 1) {
                $errmess = "Извините. Данные по этому автомобилю не найдены.";
				$errcode = 2; break;
            }

			$upload_dir = dirname($_SERVER['SCRIPT_FILENAME']).'/photo/'.$cust_id;
			$upload_url = self::FullUrl().'/photo/'.$cust_id;
			
			if( !is_dir( $upload_dir ) && !( 
					mkdir( $upload_dir.'/files', 0777, true ) &&
					mkdir( $upload_dir.'/img', 0777, true )   &&
					mkdir( $upload_dir.'/tbl', 0777, true ) )) 
			{
				$errmess = self::$error;
				$errcode = 1; break;
			}
				
            $options = array(
              'upload_dir' => $upload_dir.'/files/',
              'upload_url' => $upload_url.'/files/',
			  'accept_file_types' => '/.+\.(jpeg|jpg|gif|png)$/i',
			  'max_file_size' => 2097152,
			  'max_width' => 1280,
              'max_height' => 960,
              'min_width' => 320,
              'min_height' => 240,
              'image_versions' => array(
                'img' => array(
					'save_as_name' => $car_id,
					'save_as_type' => 'jpg',
                    'upload_dir' => $upload_dir.'/img/',
                    'upload_url' => $upload_url.'/img/',
                    'max_width' => 640,
                    'max_height' => 480,
                    'jpeg_quality' => 95
                ),
			      'tbl' => array(
					'save_as_name' => $car_id,
					'save_as_type' => 'jpg',
                    'upload_dir' => $upload_dir.'/tbl/',
                    'upload_url' => $upload_url.'/tbl/',
                    'max_width' => 80,
                    'max_height' => 60
			      )
              )
			);
			$upload_handler = new UploadHandler($options);
			$data = $upload_handler->post();
			if( !$data ) return;
			
			if( isset( $data[0]->error ) ) {
				$errmess = $data[0]->error;
				$errcode = 2;
				break;
			}
			
            break;
        }

		if( $errmess ) {
			$data[0] = array( 'error' => array( 'errmess'=>'<center>Ошибка !!!<br>'.$errmess.'</center>','errcode'=>$errcode) );
		}

		echo json_encode( $data );
        return;
    }

	public function Delete()
    {

        $car_id = isset($_REQUEST["car_id"]) ? strip_tags($_REQUEST["car_id"]) : '';
		$index	= isset($_REQUEST["index"]) ? strip_tags($_REQUEST["index"]) : 0;
		$errcode = 0;
		$errmess = "";
        		
        while (true)
        {
			if( !isset( $_SESSION['cust_id'] ) || !$_SESSION['cust_id'] ) {
				$errmess = "Вы не выполнили вход в систему<br>или Ваша сессия закончилась по таймауту."; 
				$errcode = 999; break;
			}
			$cust_id =  $_SESSION['cust_id'];

			if ( !is_numeric($car_id) ) {
                $errmess = "Нарушение формата данных.";
				$errcode = 2; break;
            }
            if( $this->db == NULL ) {
                $errmess = self::$error;
				$errcode = 1; break;
            }
            $db = $this->db;
                                    
			$photo_dir = dirname($_SERVER['SCRIPT_FILENAME']).'/photo';
			$file_name = $car_id . ( $index ? '_'.$index : '' ) . '.jpg';
			
// Проверяем существование
            $sqlreq = "SELECT owner_id FROM cars WHERE car_id=" . $car_id;
            $recset = $db->query( $sqlreq );
            if(!($row = $recset->fetch(PDO::FETCH_ASSOC)) )
				break;
				
			$cust_id = $row['owner_id'];
			@unlink( $photo_dir.'/'.$cust_id.'/img/'.$file_name );
			@unlink( $photo_dir.'/'.$cust_id.'/tbl/'.$file_name );

            $recset->closeCursor();
			
            break;
        }

        header("Content-type: text/script;charset=utf-8");
		echo json_encode( array( 'errcode'=>$errcode, 'errmess'=>$errmess ) );
        return;
    }

	public function GetImage()
    {

        $im     = isset($_REQUEST["im"]) ? strip_tags($_REQUEST["im"]) : '';
        $car_id = isset($_REQUEST["car_id"]) ? strip_tags($_REQUEST["car_id"]) : '';
		$index	= isset($_REQUEST["index"]) ? strip_tags($_REQUEST["index"]) : 0;
		$errcode = 0;
        
        while (true)
        {
			if ( ($im != 'img' && $im != 'tbl') || !is_numeric($car_id) || !is_numeric($index) ) {
				$errcode = 2; break;
            }
            if( $this->db == NULL ) {
				$errcode = 1; break;
            }
            $db = $this->db;
            
			$photo_dir = dirname($_SERVER['SCRIPT_FILENAME']).'/photo';
			$file_name = $car_id . ( $index ? '_'.$index : '' ) . '.jpg';
			$null_path = $photo_dir.'/0/'.$im.'/0.jpg';
			
// Проверяем существование
            $sqlreq = "SELECT owner_id FROM cars WHERE car_id=" . $car_id;
            $recset = $db->query( $sqlreq );
            if(!($row = $recset->fetch(PDO::FETCH_ASSOC)) ) {
				$cust_id = 0;
				$file_path = $null_path;
			}
			else {
				$cust_id = $row['owner_id'];
				$file_path = $photo_dir.'/'.$cust_id.'/'.$im.'/'.$file_name;
				if( !is_file($file_path) ) $file_path = $null_path;
			}
            $recset->closeCursor();
			
            break;
        }

		if( $errcode ) return;

		header('Pragma: no-cache');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header("Content-Type: image/jpg"); 
		echo file_get_contents($file_path);
			
        return;
    }

} // End of CarImages

?>
